package com.wchat.service.impl;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wchat.bean.entity.Friends;
import com.wchat.bean.entity.Groups;
import com.wchat.bean.entity.Users;
import com.wchat.bean.model.MsgPayload;
import com.wchat.bean.model.Session;
import com.wchat.bean.model.body.EventBody;
import com.wchat.bean.model.enums.HeaderTypeEm;
import com.wchat.bean.model.enums.TypeEm;
import com.wchat.mapper.FriendsMapper;
import com.wchat.mapper.GroupsMapper;
import com.wchat.mapper.UserGroupsMapper;
import com.wchat.mapper.UsersMapper;
import com.wchat.server.ClientManager;
import com.wchat.service.AddressBookService;
import com.wchat.utils.JwtUtil;
import com.wchat.utils.R;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.Set;

/**
 * @author : willian fu
 * @date : 2021/8/30
 */
@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private FriendsMapper friendsMapper;

    @Autowired
    private UserGroupsMapper userGroupsMapper;

    @Autowired
    private GroupsMapper groupsMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private ClientManager clientManager;


    @Override
    public Object getAddressBookFriends() {
        Integer userId = jwtUtil.jwtGetUser().getUserId();
        return R.ok(friendsMapper.getFriends(userId, 1));
    }

    @Override
    public Object getAddressBookGroups() {
        Integer userId = jwtUtil.jwtGetUser().getUserId();
        Set<Integer> groups = userGroupsMapper.getUserGroups(userId);
        if (groups.size() > 0) {
            return R.ok(groupsMapper.selectList(new QueryWrapper<Groups>().in("id", groups)));
        }
        return R.ok(Collections.EMPTY_LIST);
    }

    @Override
    public Object searchFriends(String name) {
        Integer userId = jwtUtil.jwtGetUser().getUserId();
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.select("user_id, user_name, nick, avatar, sex")
                .ne("user_id", userId);
        if (Validator.isNumber(name)) {
            wrapper.like("mobile", name);
        } else {
            wrapper.like("user_name", name);
        }
        return R.ok(usersMapper.selectList(wrapper));
    }

    @Override
    public Object addFriends(Integer userId, String remark) {
        Integer myId = jwtUtil.jwtGetUser().getUserId();
        try {
            Friends friends = Friends.builder()
                    .userId(myId)
                    .friendId(userId)
                    .remark(remark)
                    .status(0)
                    .created(GregorianCalendar.getInstance().getTime())
                    .build();
            friendsMapper.insert(friends);
            clientManager.sendEvent(userId, TypeEm.FRIEND_ADD_REQ,
                    EventBody.builder().id(friends.getId().toString()).userId(myId).build());
            return R.ok("添加成功，等待对方通过");
        } catch (Exception e) {
            return R.badRequest("添加失败，不可重复添加");
        }

    }

    @Override
    public Object updateFriendsRemark(Integer friendId, String remark) {
        Integer myId = jwtUtil.jwtGetUser().getUserId();
        Friends friends = friendsMapper.selectById(friendId);
        Friends build = Friends.builder().id(friendId).build();
        if (friends.getFriendId().equals(myId)) {
            build.setFRemark(remark);
        } else {
            build.setURemark(remark);
        }
        friendsMapper.updateById(build);
        return R.ok("修改备注成功");
    }

    @Override
    public Object delFriends(Integer friendId) {
        Integer myId = jwtUtil.jwtGetUser().getUserId();
        Friends friends = friendsMapper.selectById(friendId);
        friendsMapper.deleteById(friendId);
        Session session = clientManager.getSession(myId);
        if (null != session) {
            session.getFriends().remove(friends.getUserId().equals(myId) ?
                    friends.getFriendId() : friends.getUserId());
        }
        return R.ok("删除好友成功");
    }

    @Override
    public Object getNewFriends() {
        Integer userId = jwtUtil.jwtGetUser().getUserId();
        return R.ok(friendsMapper.getNewFriends(userId));
    }

    @Override
    public Object confirmFriendsRequest(Integer id) {
        friendsMapper.updateById(Friends.builder().id(id).status(1).build());
        Friends friends = friendsMapper.selectById(id);
        Session mSession = clientManager.getSession(friends.getUserId());
        Session fSession = clientManager.getSession(friends.getFriendId());
        if (null != mSession) {
            mSession.getFriends().add(friends.getFriendId());
        }
        if (null != fSession) {
            fSession.getFriends().add(friends.getUserId());
        }
        clientManager.sendEvent(friends.getUserId(), TypeEm.FRIEND_ADD,
                EventBody.builder().id(friends.getId().toString()).userId(friends.getFriendId()).build());
        return R.ok("添加成功");
    }
}
